use neurosymbolic_ai::{
    neural::{Activation, Layer, NeuralNetwork},
    symbolic::{Fact, Rule, SymbolicEngine},
    NeuroSymbolicSystem,
};

fn main() {
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║        神经符号AI系统 - Neuro-Symbolic AI System         ║");
    println!("╚════════════════════════════════════════════════════════════╝\n");

    // 运行示例
    example_1_animal_classification();
    println!("\n{}\n", "=".repeat(60));
    example_2_weather_reasoning();
    println!("\n{}\n", "=".repeat(60));
    example_3_medical_diagnosis();
}

/// 示例1: 动物分类系统
fn example_1_animal_classification() {
    println!("【示例1】动物分类系统");
    println!("{}", "-".repeat(60));

    // 1. 创建神经网络 (用于特征识别)
    let mut nn = NeuralNetwork::new();
    nn.add_layer(Layer::new(4, 6, Activation::ReLU));
    nn.add_layer(Layer::new(6, 3, Activation::Sigmoid));

    // 2. 训练数据: [has_fur, has_feathers, can_fly, lives_in_water] -> [mammal, bird, fish]
    let training_data = vec![
        // 哺乳动物
        (vec![1.0, 0.0, 0.0, 0.0], vec![1.0, 0.0, 0.0]), // 猫
        (vec![1.0, 0.0, 0.0, 0.0], vec![1.0, 0.0, 0.0]), // 狗
        (vec![1.0, 0.0, 0.0, 1.0], vec![1.0, 0.0, 0.0]), // 海豚
        // 鸟类
        (vec![0.0, 1.0, 1.0, 0.0], vec![0.0, 1.0, 0.0]), // 鹰
        (vec![0.0, 1.0, 1.0, 0.0], vec![0.0, 1.0, 0.0]), // 麻雀
        // 鱼类
        (vec![0.0, 0.0, 0.0, 1.0], vec![0.0, 0.0, 1.0]), // 金鱼
        (vec![0.0, 0.0, 0.0, 1.0], vec![0.0, 0.0, 1.0]), // 鲨鱼
    ];

    println!("\n训练神经网络...");
    nn.train_batch(&training_data, 0.1, 1000);

    // 3. 创建符号推理引擎
    let mut symbolic = SymbolicEngine::new();

    // 添加分类规则
    symbolic.add_rule(Rule::new(
        "mammals_warm_blooded",
        vec![Fact::new("category", vec!["mammal".to_string()])],
        Fact::new("warm_blooded", vec!["true".to_string()]),
        1.0,
    ));

    symbolic.add_rule(Rule::new(
        "birds_can_lay_eggs",
        vec![Fact::new("category", vec!["bird".to_string()])],
        Fact::new("lays_eggs", vec!["true".to_string()]),
        1.0,
    ));

    symbolic.add_rule(Rule::new(
        "fish_breathe_water",
        vec![Fact::new("category", vec!["fish".to_string()])],
        Fact::new("breathes_underwater", vec!["true".to_string()]),
        1.0,
    ));

    // 4. 创建神经符号系统
    let mut system = NeuroSymbolicSystem::new(nn, symbolic);
    system.set_neural_mapping(0, "category".to_string());
    system.set_neural_mapping(1, "category".to_string());
    system.set_neural_mapping(2, "category".to_string());
    system.set_confidence_threshold(0.5);

    // 5. 测试: 未知动物
    println!("\n测试未知动物:");
    let unknown_animal = vec![1.0, 0.0, 0.0, 0.0]; // 有毛, 无羽毛, 不会飞, 不在水中
    let prediction = system.neural().predict(&unknown_animal);
    
    println!("特征: 有毛, 无羽毛, 不会飞, 不在水中");
    println!("神经网络预测: 哺乳动物={:.2}, 鸟类={:.2}, 鱼类={:.2}", 
             prediction[0], prediction[1], prediction[2]);

    // 基于预测添加事实
    if prediction[0] > 0.5 {
        system.add_fact(Fact::new("category", vec!["mammal".to_string()]));
        println!("\n分类结果: 哺乳动物");
        
        // 符号推理得出更多结论
        let new_facts = system.reason(5);
        println!("符号推理推导出 {} 个新事实:", new_facts);
        
        for fact in system.query("warm_blooded") {
            println!("  - {}", fact);
        }
    }
}

/// 示例2: 天气推理系统
fn example_2_weather_reasoning() {
    println!("【示例2】天气推理系统");
    println!("{}", "-".repeat(60));

    // 1. 创建神经网络 (传感器数据 -> 天气特征)
    let mut nn = NeuralNetwork::new();
    nn.add_layer(Layer::new(3, 4, Activation::ReLU));
    nn.add_layer(Layer::new(4, 3, Activation::Sigmoid));

    // 训练数据: [temperature, humidity, wind_speed] -> [hot, humid, windy]
    let training_data = vec![
        (vec![35.0/50.0, 0.8, 0.2], vec![1.0, 1.0, 0.0]), // 热且潮湿
        (vec![10.0/50.0, 0.3, 0.8], vec![0.0, 0.0, 1.0]), // 冷且有风
        (vec![25.0/50.0, 0.5, 0.3], vec![0.5, 0.5, 0.0]), // 温和
    ];

    println!("\n训练神经网络...");
    nn.train_batch(&training_data, 0.01, 400);

    // 2. 创建符号推理引擎
    let mut symbolic = SymbolicEngine::new();

    // 添加天气推理规则
    symbolic.add_rule(Rule::new(
        "rain_prediction",
        vec![
            Fact::new("weather", vec!["hot".to_string()]),
            Fact::new("weather", vec!["humid".to_string()]),
        ],
        Fact::new("likely", vec!["rain".to_string()]),
        0.8,
    ));

    symbolic.add_rule(Rule::new(
        "storm_prediction",
        vec![
            Fact::new("likely", vec!["rain".to_string()]),
            Fact::new("weather", vec!["windy".to_string()]),
        ],
        Fact::new("warning", vec!["storm".to_string()]),
        0.9,
    ));

    symbolic.add_rule(Rule::new(
        "stay_indoor",
        vec![Fact::new("warning", vec!["storm".to_string()])],
        Fact::new("advice", vec!["stay_indoor".to_string()]),
        1.0,
    ));

    // 3. 创建神经符号系统
    let mut system = NeuroSymbolicSystem::new(nn, symbolic);
    system.set_neural_mapping(0, "weather".to_string());
    system.set_neural_mapping(1, "weather".to_string());
    system.set_neural_mapping(2, "weather".to_string());

    // 4. 测试: 今日天气
    println!("\n当前传感器读数:");
    let sensor_data = vec![32.0/50.0, 0.85, 0.7]; // 温度32°C, 湿度85%, 风速7m/s
    println!("  温度: 32°C");
    println!("  湿度: 85%");
    println!("  风速: 7 m/s");

    // 感知和推理
    let all_facts = system.perceive_and_reason(&sensor_data, 100);

    println!("\n推理结果:");
    for fact in all_facts {
        println!("  ✓ {}", fact);
    }

    // 显示推理过程
    system.show_inference_log();
}

/// 示例3: 医疗诊断系统
fn example_3_medical_diagnosis() {
    println!("【示例3】医疗诊断系统");
    println!("{}", "-".repeat(60));

    // 1. 创建神经网络 (症状识别)
    let mut nn = NeuralNetwork::new();
    nn.add_layer(Layer::new(5, 8, Activation::ReLU));
    nn.add_layer(Layer::new(8, 4, Activation::Sigmoid));

    // 训练数据: [fever, cough, fatigue, headache, sore_throat] -> [cold, flu, allergy, healthy]
    let training_data = vec![
        // 感冒
        (vec![1.0, 1.0, 0.5, 0.5, 1.0], vec![1.0, 0.0, 0.0, 0.0]),
        (vec![0.8, 1.0, 0.6, 0.4, 0.9], vec![1.0, 0.0, 0.0, 0.0]),
        // 流感
        (vec![1.0, 1.0, 1.0, 1.0, 0.5], vec![0.0, 1.0, 0.0, 0.0]),
        (vec![0.9, 0.8, 1.0, 0.9, 0.4], vec![0.0, 1.0, 0.0, 0.0]),
        // 过敏
        (vec![0.0, 0.5, 0.3, 0.2, 0.4], vec![0.0, 0.0, 1.0, 0.0]),
        (vec![0.0, 0.6, 0.4, 0.3, 0.5], vec![0.0, 0.0, 1.0, 0.0]),
        // 健康
        (vec![0.0, 0.0, 0.0, 0.0, 0.0], vec![0.0, 0.0, 0.0, 1.0]),
    ];

    println!("\n训练神经网络...");
    nn.train_batch(&training_data, 0.12, 1000);

    // 2. 创建符号推理引擎
    let mut symbolic = SymbolicEngine::new();

    // 添加诊断规则
    symbolic.add_rule(Rule::new(
        "cold_rest",
        vec![Fact::new("diagnosis", vec!["cold".to_string()])],
        Fact::new("treatment", vec!["rest_and_hydration".to_string()]),
        0.95,
    ));

    symbolic.add_rule(Rule::new(
        "flu_medication",
        vec![Fact::new("diagnosis", vec!["flu".to_string()])],
        Fact::new("treatment", vec!["antiviral_medication".to_string()]),
        0.9,
    ));

    symbolic.add_rule(Rule::new(
        "flu_isolation",
        vec![Fact::new("diagnosis", vec!["flu".to_string()])],
        Fact::new("advice", vec!["isolate_to_prevent_spread".to_string()]),
        1.0,
    ));

    symbolic.add_rule(Rule::new(
        "allergy_antihistamine",
        vec![Fact::new("diagnosis", vec!["allergy".to_string()])],
        Fact::new("treatment", vec!["antihistamine".to_string()]),
        0.95,
    ));

    symbolic.add_rule(Rule::new(
        "severe_flu_hospital",
        vec![
            Fact::new("diagnosis", vec!["flu".to_string()]),
            Fact::new("severity", vec!["high".to_string()]),
        ],
        Fact::new("advice", vec!["seek_hospital_care".to_string()]),
        1.0,
    ));

    // 3. 创建神经符号系统
    let mut system = NeuroSymbolicSystem::new(nn, symbolic);
    system.set_neural_mapping(0, "diagnosis".to_string());
    system.set_neural_mapping(1, "diagnosis".to_string());
    system.set_neural_mapping(2, "diagnosis".to_string());
    system.set_neural_mapping(3, "diagnosis".to_string());
    system.set_confidence_threshold(0.6);

    // 4. 患者症状
    println!("\n患者症状:");
    let symptoms = vec![0.9, 0.8, 0.95, 0.85, 0.4];
    println!("  发烧: 高");
    println!("  咳嗽: 是");
    println!("  疲劳: 严重");
    println!("  头痛: 是");
    println!("  喉咙痛: 轻微");

    // 神经网络诊断
    let diagnosis = system.neural().predict(&symptoms);
    println!("\n神经网络诊断置信度:");
    println!("  感冒: {:.2}%", diagnosis[0] * 100.0);
    println!("  流感: {:.2}%", diagnosis[1] * 100.0);
    println!("  过敏: {:.2}%", diagnosis[2] * 100.0);
    println!("  健康: {:.2}%", diagnosis[3] * 100.0);

    // 添加诊断事实
    if diagnosis[1] > 0.6 {
        system.add_fact(Fact::new("diagnosis", vec!["flu".to_string()]));
        system.add_fact(Fact::new("severity", vec!["high".to_string()]));
    }

    // 符号推理得出治疗建议
    println!("\n符号推理...");
    let new_facts = system.reason(10);
    println!("推导出 {} 个新建议\n", new_facts);

    println!("治疗建议:");
    for fact in system.query("treatment") {
        println!("  💊 {}", fact);
    }

    for fact in system.query("advice") {
        println!("  ⚠️  {}", fact);
    }

    // 显示完整推理过程
    system.show_inference_log();
}

